package com.java.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.java.mapper.DictMapper;
import com.java.pojo.vo.DictVo;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelLisenters extends AnalysisEventListener<DictVo> {


    private DictMapper dictMapper;

    public ExcelLisenters(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }
    private static final int BATCH_COUNT = 5;
    List<DictVo> list = new ArrayList();
    /**
     * 这个每一条数据解析都会来调用
     */
    @Override
    public void invoke(DictVo data, AnalysisContext context) {
        list.add(data);
        if(list.size() >= BATCH_COUNT){
            saveData();
            list.clear();
        }

    }

    private void saveData(){
        dictMapper.insertBatch(list);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }
}
